package edu.sctu.practice.class02.xuejiahua.assign08.ass03;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by Dom_xuejiahua on 2015/12/24.
 */
public class Client extends Frame implements Runnable,ActionListener {
    Button b = new Button("获取图像");
    ImageCanvas canvas;

    Client() {
        super("I am a client");
        setSize(320, 200);
        setVisible(true);
        b.addActionListener(this);
        add(b, BorderLayout.NORTH);
        canvas = new ImageCanvas();
        add(canvas, BorderLayout.CENTER);
        Thread thread = new Thread(this);
        validate();
        addWindowListener(new WindowAdapter() {
                              public void windowClosing(WindowEvent e) {
                                  System.exit(0);
                              }
                          }
        );
        thread.start();
    }

    public void actionPerformed(ActionEvent event) {
        byte b[] = "请发图像".trim().getBytes();
        try {
            InetAddress address = InetAddress.getByName("127.0.0.1");
            DatagramPacket data = new DatagramPacket(b, b.length, address, 1234); //创建数据包，该数据包的目标地址和端口分别是
            //address和1234，其中的数据为数组b中的全部字节。
            DatagramSocket mailSend = new DatagramSocket(); //创建负责发送数据的DatagramSocket对象。
            mailSend.send(data);                   // mailSend发送数据data。
        } catch (Exception e) {
        }
    }

    public void run() {
        DatagramPacket pack = null;
        DatagramSocket mailReceive = null;
        byte b[] = new byte[8192];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            pack = new DatagramPacket(b, b.length);
            mailReceive = new DatagramSocket(5678); //创建在端口5678负责收取数据包的DatagramSocket对象。
        } catch (Exception e) {
        }
        try {
            while (true) {
                mailReceive.receive(pack);
                String message = new String(pack.getData(), 0, pack.getLength());
                if (message.startsWith("end")) {
                    break;
                }
                out.write(pack.getData(), 0, pack.getLength());
            }
            byte imagebyte[] = out.toByteArray();
            out.close();
            Toolkit tool = getToolkit();
            Image image = tool.createImage(imagebyte);
            canvas.setImage(image);
            canvas.repaint();
            validate();
        } catch (IOException e) {
        }
    }

    public static void main(String args[]) {
        new Client();
    }

}
